package com.example;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;


public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap
                //指定线程模型
                .group(group)
                //指定IO类型
                .channel(NioSocketChannel.class)
                //io处理逻辑
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                });

        //建立连接
        final Channel channel = bootstrap.connect("127.0.0.1", 8000)
                .addListener(future -> {
                    if (future.isSuccess()){
                        System.out.println("连接成功");
                    }else {
                        System.out.println("连接失败");
                    }
                })
                .channel();

        while (true){
            channel.writeAndFlush(LocalDateTime.now()+": hello world");
            TimeUnit.SECONDS.sleep(2);
        }
    }
}
